package com.ai.zuochengyun.phase01.class07;

import java.util.Stack;

public class Code05_ReverseStackUseRecursive {

    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        reverse(stack);
        while (!stack.isEmpty()) {
            System.out.println(stack.pop());
        }
    }

    public static void reverse(Stack<Integer> stack) {
        if (stack.isEmpty()) {
            return;
        }
        // 弹出底部的元素，其余的下移
        int num = f(stack);
        // r1 r2 r3
        reverse(stack);
        stack.push(num);
    }

    /**
     * 移除底部元素，然后让上面的元素整体下沉
     * 返回移除掉的元素
     * @param stack
     * @return
     */
    private static int f(Stack<Integer> stack) {
        // 弹出栈顶的元素
        Integer res = stack.pop();
        if (stack.isEmpty()) {
            return res;
        }
        int last = f(stack);
        stack.push(res);
        return last;
    }
}
